package common

import (
	"log"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)

var db *gorm.DB

func init() {
	mysqlDB, err := gorm.Open(mysql.New(mysql.Config{
		DSN:                           "root:10010@tcp(localhost:3306)/test2?charset=utf8mb4&parseTime=True&loc=Local&clientFoundRows=true",
		DefaultStringSize:             256,
		DisableDatetimePrecision:      true,
		DontSupportRenameIndex:        true,
		DontSupportNullAsDefaultValue: true,
		SkipInitializeWithVersion:     false,
	}), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
		SkipDefaultTransaction: true,
	})
	if err != nil {
		log.Fatalln("mysql初始化失败", err.Error())
	}
	sqlDB, err := mysqlDB.DB()
	if err != nil {
		log.Fatalln("mysql初始化失败", err.Error())
	}
	sqlDB.SetMaxOpenConns(10)
	sqlDB.SetMaxIdleConns(5)
	sqlDB.SetConnMaxLifetime(10 * time.Minute)
	sqlDB.SetConnMaxIdleTime(5 * time.Minute)
	db = mysqlDB
}

func MysqlDB() *gorm.DB {
	return db
}
